// pages/showqr/showqr.js
import {
  ds
} from '../../tools/data'
import {
  checkTook,
  checkTool
} from '../../tools/check'
import {
  ui
} from '../../tools/ui'
import {
  users
} from '~/tools/users'
import {
  dsx
} from '~/tools/datax'
import {
  nav2
} from '~/tools/nav2'
import {
  pages
} from '~/tools/pages'

Page({
  data: {
    items: ['空桶押金'], // '订单线下支付'
    values: {
      title: '',
      remark: '',
      fee: '',
      barrel: '',
      add: 0,
      ret: 0
    },
    canChooseTitle: true,
    barrel: {},
    userInfo: {},
    options: {}
  },
  async onLoad(options) {
    const {
      title,
      orderId,
      userOpenId,
      nickName,
      goodsName,
      add
    } = options
    this.options = options
    // console.log(options)
    if (title) {
      this.setData({
        canChooseTitle: false
      })
    }

    let values = this.data.values
    values = {
      ...options
    }
    // console.log(values)
    values.title = title ? title : this.data.items[0]
    values.add = parseInt(add || 0)
    this.setData({
      values
    })

    await this.loadBarrelInfo();
    ui.loading(false)
  },
  async loadBarrelInfo() {
    const {
      userOpenId
    } = this.data.values
    const res = await users.getUserByOpenid(userOpenId, {
      barrelPay: true
    })
    // console.log(userOpenId, res)
    const barrel = {
      barrel: res.barrelPay?.barrel || 0
    }
    this.setData({
      barrel,
      userInfo: res
    })
    // console.log(res)
  },
  async updateBarrel() {
    const {
      values,
      barrel,
      userInfo
    } = this.data
    const bnum = this.calcBarrel()
    // console.log(bnum, values)
    if (bnum < 0) {
      ui.toast(false, '桶数不能小于0')
      return
    }

    const res = await ui.confirmx(`现有${barrel.barrel} + 投放${values.add} - 回收${values.ret} = 更新为${bnum}`)
    if (!res) return
    const ures = await dsx.cloudUpdateByIds('users', [userInfo._id], {}, {
      barrelPay: {
        barrel: bnum
      }
    })
    // console.log(ures)
    if (ures.result.errMsg.endsWith(':ok')) {
      await ui.confirmx('更新成功')
      if (this.options.callBeforeCompleteOrder) {
        pages.back((prePage) => {
          prePage.updateBarrelInfoCallback();
        })
      } else {
        this.onLoad(this.options)
        ui.loading()
      }
    }
  },
  onTapItem() {
    if (!this.data.canChooseTitle) return

    ui.actionSheet(this.data.items, (title, index) => {
      const values = this.data.values
      values.title = title
      this.setData({
        values
      })
    })
  },
  // 出示收款码
  onShowQr() {
    if (!checkTool.check(this.getFields())) return

    const values = this.data.values
    if (!values.title || !(values.fee >= 0)) {
      ui.toast(false, '请填写完整')
      return
    }
    wx.navigateTo({
      url: '/pages/qr/qrcode?param=' + JSON.stringify(this.data.values),
    })
  },
  // 已现金收款
  // onCashTap() {
  //   if (!checkTool.check(this.getFields())) return
  //   ui.confirm('确定现金收款吗？', res => {
  //     if (!res) return
  //     this.doCashTap()
  //   })
  // },
  getFields() {
    const {
      values
    } = this.data
    const fields = [{
      value: values.barrel,
      allowEmpty: values.title != '空桶押金',
      title: '空桶数量'
    }, {
      value: values.fee,
      regex: checkTool.CommonRegex.decimal,
      title: '收款金额'
    }]
    return fields
  },
  // doCashTap() {
  //   const {
  //     userOpenId,
  //     title,
  //     orderId,
  //     barrel,
  //     fee,
  //     remark
  //   } = this.data.values

  //   if (title == '空桶押金') {
  //     ds.cloudUpdateWhere('users', {
  //       _openid: userOpenId
  //     }, {
  //       barrel,
  //       pladge: fee
  //     }, res => {
  //       // console.log(res)
  //       const success = res.result.errMsg.endsWith(':ok')
  //       ui.toast(success, null, (success) => {
  //         if (success) wx.navigateBack()
  //       })
  //     })
  //   } else if (title == '步梯费') {
  //     ds.cloudUpdate('orders', orderId, {
  //       stepFee: `_.inc(${fee})`
  //     }, res => {
  //       // console.log(orderId, res)
  //       const success = res.result.errMsg.endsWith(':ok')
  //       ui.toast(success, null, (success) => {
  //         if (success) wx.navigateBack()
  //       })
  //     })
  //   }
  // },
  onValueChange(e) {
    const {
      barrel,
      values
    } = this.data
    const value = e.detail.value,
      name = e.target.dataset.name;

    if (name == 'fee') values[name] = parseInt(value)
    else if (name == 'barrel') {
      const nbarrel = parseInt(value)
      this.setData({
        'barrel.barrel': nbarrel
      })
      values[name] = nbarrel
    } else values[name] = value

    values.barrel = this.calcBarrel() + '';
    this.setData({
      values
    })
    // console.log(values)
  },
  calcBarrel() {
    const {
      barrel,
      values
    } = this.data
    const now = barrel.barrel || 0
    values.add = parseInt(values.add || 0)
    values.ret = parseInt(values.ret || 0)
    this.setData({
      values
    })
    return parseInt(now + values.add - values.ret);
  }

})